package com.shuorikeji.huohuo.http;

import android.util.Log;

import com.shuorikeji.huohuo.utils.BusinessUtils;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.concurrent.TimeUnit;

import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import okhttp3.ConnectionPool;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava.RxJavaCallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

/**
 * Retofit网络请求工具类
 *
 * @author wxl
 */
public class RetrofitUtils {
    private static Retrofit mRetrofit;

    public static Retrofit newInstence() {
        mRetrofit = null;
        Gson gHead = new GsonBuilder().disableHtmlEscaping().create();
        OkHttpClient.Builder builder = new OkHttpClient.Builder().connectTimeout(50, TimeUnit.SECONDS)
                .connectTimeout(50 * 1000, TimeUnit.MILLISECONDS)
                .readTimeout(50 * 1000, TimeUnit.MILLISECONDS)
                .connectionPool(new ConnectionPool(5, 1, TimeUnit.SECONDS))
                .sslSocketFactory(createSSLSocketFactory(), xtm)
                .addInterceptor(chain -> {
                    Request originalRequest = chain.request();
                    Request.Builder requestBuilder = originalRequest.newBuilder()
                            .addHeader("Content-Type", "application/json; charset=utf-8");
                    if (BusinessUtils.getUserInfo() != null) {
                        requestBuilder.addHeader("token", BusinessUtils.getUserInfo().getToken());
                    }
                    requestBuilder.method(originalRequest.method(), originalRequest.body());
                    Request request = requestBuilder.build();
                    Log.i("wxl", request.toString());
                    return chain.proceed(request);
                })
                .retryOnConnectionFailure(false);// 失败重发

        mRetrofit = new Retrofit.Builder()
                .client(builder.build())//添加一个client,不然retrofit会自己默认添加一个   //公众号H5接口
                .baseUrl(ApiUrl.API_BASE_URL)
                .addConverterFactory(GsonConverterFactory.create(gson))
                .addCallAdapterFactory(RxJavaCallAdapterFactory.create())
                .build();
        return mRetrofit;
    }


    private static X509TrustManager xtm = new X509TrustManager() {
        @Override
        public void checkClientTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public void checkServerTrusted(X509Certificate[] chain, String authType) {
        }

        @Override
        public X509Certificate[] getAcceptedIssuers() {
            X509Certificate[] x509Certificates = new X509Certificate[0];
            return x509Certificates;
        }
    };

    private static SSLSocketFactory createSSLSocketFactory() {
        SSLSocketFactory sslSocketFactory = null;
        try {
            SSLContext sslContext = SSLContext.getInstance("TLS");
            sslContext.init(null, new TrustManager[]{xtm}, new SecureRandom());
            sslSocketFactory = sslContext.getSocketFactory();
            return sslSocketFactory;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (KeyManagementException e) {
            e.printStackTrace();
        }
        return null;
    }

    public static APIService getService() {
        return newInstence().create(APIService.class);
    }

    public static Gson gson = new GsonBuilder().disableHtmlEscaping().create();
}
